﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace PengSW.History
{
    public class FileHistory : ObservableCollection<string>
    {
        public FileHistory(System.Configuration.ApplicationSettingsBase aSettings = null, string aPropertyName = "History", int aMaxCount = 10)
        {
            _Settings = aSettings;
            _PropertyName = aPropertyName;
            MaxCount = aMaxCount;
            if (_Settings != null && !string.IsNullOrWhiteSpace(_PropertyName))
            {
                ReadFromString(_Settings.GetType().GetProperty(_PropertyName).GetValue(_Settings).ToString());
            }
        }

        public void RecordHistory(string aFileName)
        {
            if (string.IsNullOrWhiteSpace(aFileName)) return;
            if (Contains(aFileName)) Remove(aFileName);
            Insert(0, aFileName);
            while (Count > MaxCount) RemoveAt(MaxCount);
            _Settings.GetType().GetProperty(_PropertyName).SetValue(_Settings, CreateString());
            _Settings?.Save();
        }

        public int MaxCount { get; }
        private System.Configuration.ApplicationSettingsBase _Settings;
        private string _PropertyName;

        #region 序列化

        public void ReadFromString(string aString)
        {
            var aFileNames = (from r in aString.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries) where !string.IsNullOrWhiteSpace(r) select r).Distinct();
            Clear();
            foreach (string aFileName in aFileNames)
            {
                Add(aFileName);
                if (Count >= MaxCount) break;
            }
        }
        public string CreateString()
        {
            StringBuilder aStringBuilder = new StringBuilder();
            foreach (string aFileName in this)
            {
                aStringBuilder.AppendLine(aFileName);
            }
            return aStringBuilder.ToString();
        }

        #endregion
    }
}
